//
//  MapViewController.m
//  FVQuickMessage
//
//  Created by dllo on 16/8/11.
//  Copyright © 2016年 zty. All rights reserved.
//

#import "MapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "MapDetailViewController.h"
#import "TransMapViewController.h"
#import "BusModel.h"
#import "WalkModel.h"
#define APIKey @"922430c85ae662b5762088edebaeedab"

@interface MapViewController ()<MAMapViewDelegate, AMapSearchDelegate,  UIGestureRecognizerDelegate>
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) CLLocation *currentLocation;
@property (nonatomic, strong) NSArray<AMapPOI *> *pois;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *annotations;
@property (nonatomic, strong) MAPointAnnotation *annotation;
@property (nonatomic, retain) UILongPressGestureRecognizer *longPressGestureRecongnizer;
//目的地坐标
@property (nonatomic, strong) MAPointAnnotation *destinationPoint;
@property (nonatomic, strong) NSArray *pathPolylines;
@property (nonatomic, strong) NSString *str;
@property (nonatomic, strong) AMapWalkingRouteSearchRequest *walkRequest;
@property (nonatomic, strong) AMapTransitRouteSearchRequest *transRequest;
@property (nonatomic, strong) AMapDrivingRouteSearchRequest *drivingRequest;
@property (nonatomic, strong) TransMapViewController *childVC;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) WalkModel *walkmodel;

@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.modelArray = [NSMutableArray array];
    [self initMapView];
    [self initController];
    [self initSearch];
    [self initGest];
    self.childVC = [[TransMapViewController alloc] init];
    void(^retu)() = ^{
        [UIView animateWithDuration:1 delay:0.1 usingSpringWithDamping:1 initialSpringVelocity:0.05 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.childVC.view.frame = CGRectMake(0, -HEIGHT / 3, WIDTH, HEIGHT / 3);
         
        //通知中心
            [[NSNotificationCenter defaultCenter]postNotificationName:@"move" object:nil];
        } completion:^(BOOL finished) {
            
        }];

        
        
    };
    self.childVC.block = retu;
    [self addChildViewController:_childVC];
    _childVC.view.frame = CGRectMake(0, -HEIGHT / 3, WIDTH, HEIGHT / 3);
    [self.view addSubview:_childVC.view];

   
    // Do any additional setup after loading the view.
}
//初始化手势
-(void)initGest{
    _longPressGestureRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longAPress:)];
    _longPressGestureRecongnizer.minimumPressDuration = 1;
    _longPressGestureRecongnizer.delegate = self;
    [_mapView addGestureRecognizer:_longPressGestureRecongnizer];
    
}
-(void)longAPress:(UILongPressGestureRecognizer *)gesture{
    
    
    if (gesture.state == UIGestureRecognizerStateBegan) {
        //转换坐标 屏幕坐标和地图经纬度
        CLLocationCoordinate2D coordinate = [_mapView convertPoint:[gesture locationInView:_mapView] toCoordinateFromView:_mapView];
        //添加标注
        if (_destinationPoint != nil) {
            //清理
            [_mapView removeAnnotation:_destinationPoint];
            _destinationPoint = nil;
        }
        _destinationPoint = [[MAPointAnnotation alloc] init];
        _destinationPoint.coordinate = coordinate;
        _destinationPoint.title = @"目的地";
        [_mapView addAnnotation:_destinationPoint];
    }
    
}
//手势协议方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

-(void)initMapView{
    [AMapServices sharedServices].apiKey = APIKey;
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    self.mapView.delegate = self;
    self.mapView.compassOrigin = CGPointMake(_mapView.compassOrigin.x, 22);
    _mapView.scaleOrigin = CGPointMake(_mapView.scaleOrigin.x, 22);
    [self.view addSubview:_mapView];
    _mapView.showsUserLocation = YES;
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_mapView addSubview:searchButton];

    [searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).with.offset(15);
        make.bottom.equalTo(self.view).with.offset(-100);
        make.width.offset(40);
        make.height.offset(40);
    }];
    searchButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    searchButton.backgroundColor = [UIColor whiteColor];
    [searchButton setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];

    
    
}
//搜索
-(void)searchAction{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"搜一搜" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        //通知中心
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
   
    
        textField.placeholder = @"搜你所想";
        textField.textColor = [UIColor greenColor];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.borderStyle = UITextBorderStyleRoundedRect;

        
        
    }];

    [alertController addAction:[UIAlertAction actionWithTitle:@"搜索" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if (_currentLocation == nil || _search == nil) {
            NSLog(@"search faild");
            return;
        }
        AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
        request.keywords = _str;
        [_search AMapPOIAroundSearch:request];
        
        
    }]];

    
 [self presentViewController:alertController animated:YES completion:nil];

    
}
//通知中心
-(void)handleTextFieldTextDidChangeNotification:(NSNotification *)notification
{
    //可以用属性来传值 notification 有三个属性 一个name  一个是object 还一个是useinfo
    //    UITextField *textField = notification.object;
    UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
    if (alertController) {
        self.str = alertController.textFields.lastObject.text;
    }
}

-(void)initController{
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
      [_mapView addSubview:_button];

    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).with.offset(15);
        make.bottom.equalTo(self.view).with.offset(-150);
        make.width.offset(40);
        make.height.offset(40);
    }];
    
    _button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    _button.backgroundColor = [UIColor whiteColor];
     [self.button setImage:[UIImage imageNamed:@"指南针"] forState:UIControlStateNormal];
    _button.layer.cornerRadius = 5;
    [_button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
  
    
    UIButton *pathButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     [_mapView addSubview:pathButton];

    [pathButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).with.offset(15);
        make.bottom.equalTo(self.view).with.offset(-50);
        make.width.offset(40);
        make.height.offset(40);
    }];
    
    pathButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    pathButton.backgroundColor = [UIColor whiteColor];
    [pathButton setImage:[UIImage imageNamed:@"导航"] forState:UIControlStateNormal];
    [pathButton addTarget:self action:@selector(pathAction) forControlEvents:UIControlEventTouchUpInside];
   

}
-(void)pathAction{
    
    if (_destinationPoint == nil || _currentLocation == nil || _search == nil) {
        NSLog(@"导航失败");
        return;
    }else{
        
         UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [alertController addAction:[UIAlertAction actionWithTitle:@"坐车" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           self.drivingRequest = [[AMapDrivingRouteSearchRequest alloc] init];
            //设置为驾车路径规划
            _drivingRequest.strategy = 5;
            _drivingRequest.origin = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
            _drivingRequest.destination = [AMapGeoPoint locationWithLatitude:_destinationPoint.coordinate.latitude longitude:_destinationPoint.coordinate.longitude];
            [_search AMapDrivingRouteSearch:_drivingRequest];
            
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"坐公交" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.transRequest = [[AMapTransitRouteSearchRequest alloc] init];
            _transRequest.city = @"大连";
            _transRequest.strategy = 2;
            /// 公交换乘策略：0-最快捷模式；1-最经济模式；2-最少换乘模式；3-最少步行模式；4-最舒适模式；5-不乘地铁模式
            _transRequest.origin = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
            _transRequest.destination = [AMapGeoPoint locationWithLatitude:_destinationPoint.coordinate.latitude longitude:_destinationPoint.coordinate.longitude];
            [_search AMapTransitRouteSearch:_transRequest];
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"步行" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.walkRequest = [[AMapWalkingRouteSearchRequest alloc] init];
            _walkRequest.multipath = 1;
            _walkRequest.origin = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
            _walkRequest.destination = [AMapGeoPoint locationWithLatitude:_destinationPoint.coordinate.latitude longitude:_destinationPoint.coordinate.longitude];

            [_search AMapWalkingRouteSearch:_walkRequest];
        }]];
        
        
            [self presentViewController:alertController animated:YES completion:^{
            }];

        
        
        
        
    }
    
}
-(void)action{
    if (_mapView.userTrackingMode != MAUserTrackingModeFollow) {
        [_mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }
    
    
}
-(void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated{
    if (mode == MAUserTrackingModeNone) {
        //修改定位按钮图片
        [self.button setImage:[UIImage imageNamed:@"指南针"] forState:UIControlStateNormal];
    }else{
        //suoding
         [self.button setImage:[UIImage imageNamed:@"定位"] forState:UIControlStateNormal];
    }
}
-(void)initSearch{
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    
}
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    NSLog(@"userLocation:%@", userLocation.location);
    _currentLocation = [userLocation.location copy];
    
}
//当前地址
-(void)reGeoAction{
    if (_currentLocation) {
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
        [_search AMapReGoecodeSearch:request];
    }
}
//错误回调
-(void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    NSLog(@"request : %@, error : %@", request, error);
}
-(void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    //选中定位annotation的时候进行逆地理编码查询
    if ([view.annotation isKindOfClass:[MAUserLocation class]]) {
        [self reGeoAction];
    }
}
//搜索回调
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    _pois = [NSMutableArray array];
    _annotations = [NSMutableArray array];
    if (response.pois.count > 0) {
        _pois = response.pois;
     
        [_mapView removeAnnotation:_annotation];
        [_annotations removeAllObjects];
    }
    MapDetailViewController *vc = [[MapDetailViewController alloc] init];
    vc.array = _pois;

    void (^annotation)(AMapPOI *) = ^(AMapPOI *poi){
        self.annotation = [[MAPointAnnotation alloc]init];
        self.annotation.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
        self.annotation.title = poi.name;
        self.annotation.subtitle = poi.address;
        [_annotations addObject:self.annotation];
        [_mapView addAnnotation:self.annotation];
        //添加标注
        if (_destinationPoint != nil) {
            //清理
            [_mapView removeAnnotation:_destinationPoint];
            _destinationPoint = nil;
        }
        _destinationPoint = [[MAPointAnnotation alloc] init];
        _destinationPoint.coordinate =  self.annotation.coordinate;
    };
    vc.block = annotation;
    if (_pois.count == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"搜索无结果" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];

    }
    else{
    [self presentViewController:vc animated:YES completion:^{
        
    }];
    }
}

-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *resuseIndetifier = @"annotationIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:resuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:resuseIndetifier];
            //弹出气泡

            annotationView.canShowCallout = YES;

            return annotationView;
        }
    }
    return nil;
}
//路径回调
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
 
    if (response.count > 0) {
        [_mapView removeOverlays:_pathPolylines];
        _pathPolylines = nil;
        if (request == self.drivingRequest) {//驾车
            //只显示第一条
            _pathPolylines = [self polylinesForPath:response.route.paths[0]];
            [_mapView addOverlays:_pathPolylines];
        }
        else if (request == self.walkRequest){//步行
            //只显示第一条
            _pathPolylines = [self polylinesForPath:response.route.paths[0]];
            [_mapView addOverlays:_pathPolylines];

        }else{                                //公交
            //只显示第一条
            _pathPolylines = [self polylinesForTransPath:response.route.transits[0]];
            [_mapView addOverlays:_pathPolylines];
 
            
        }
        [_mapView showAnnotations:@[_destinationPoint, _mapView.userLocation] animated:YES];

        
    }
    if (request == self.transRequest) {
        [UIView animateWithDuration:1 delay:0.1 usingSpringWithDamping:1 initialSpringVelocity:0.05 options:UIViewAnimationOptionCurveEaseInOut animations:^{

            self.childVC.array = @[_modelArray, _walkmodel].copy;
            self.childVC.view.frame = CGRectMake(0, 64, WIDTH, HEIGHT / 3);
            
        } completion:^(BOOL finished) {
            
        }];

        
    }
}

-(NSArray *)polylinesForTransPath:(AMapTransit *)path{
    if (path == nil || path.segments.count == 0) {
        return nil;
    }
    NSMutableArray *polylines = [NSMutableArray array];
    [path.segments enumerateObjectsUsingBlock:^(AMapSegment * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        for (AMapBusLine *busLine in obj.buslines) {
            BusModel *model = [[BusModel alloc] init];
            model.depart = busLine.departureStop.name;
            model.arriva = busLine.arrivalStop.name;
            model.count = busLine.viaBusStops.count;
            [_modelArray addObject:model];
            
        }
        self.walkmodel = [[WalkModel alloc] init];
        _walkmodel.distance = obj.walking.distance;
        _walkmodel.duration = obj.walking.duration;
        NSUInteger count = 0;
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:obj.buslines.lastObject.polyline coordinateCount:&count parseToken:@";"];
        
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        [obj.walking.steps
  enumerateObjectsUsingBlock:^(AMapStep * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSUInteger count = 0;
            CLLocationCoordinate2D *coordinatesOther = [self coordinatesForString:obj.polyline coordinateCount:&count parseToken:@";"];
           MAPolyline *polylineOther = [MAPolyline polylineWithCoordinates:coordinatesOther count:count];
      [polylines insertObject:polylineOther atIndex:0];
        }];
        if (polyline != nil) {
        [polylines addObject:polyline];
        }
               free(coordinates), coordinates = NULL;

    }];
    return polylines;
}

-(NSArray *)polylinesForPath:(AMapPath *)path{
    if (path == nil || path.steps.count == 0) {
        return nil;
    }
    NSMutableArray *polylines = [NSMutableArray array];
    [path.steps enumerateObjectsUsingBlock:^(AMapStep * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSUInteger count = 0;
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:obj.polyline coordinateCount:&count parseToken:@";"];
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        [polylines addObject:polyline];
        free(coordinates), coordinates = NULL;
    }];
    
    return polylines;
}
-(CLLocationCoordinate2D *)coordinatesForString:(NSString *)string coordinateCount:(NSUInteger *)coordinatesCount parseToken:(NSString *)token{
    if (string == nil) {
        return  NULL;
    }
    if (token == nil) {
        token = @",";
    }
    NSString *str = @"";
    if (![token isEqualToString:@","]) {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }else{
        str = [NSString stringWithString:string];
    }
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinatesCount != NULL) {
        *coordinatesCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D *)malloc(count * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < count; i++) {
        coordinates[i].longitude = [[components objectAtIndex:2 * i] doubleValue];
        coordinates[i].latitude = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    return coordinates;
}
//导航样式
-(MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        polylineView.lineWidth = 4;
        polylineView.strokeColor = [UIColor magentaColor];
        return polylineView;
    }
    return nil;
}
@end
